package com.demon;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

/**
 * Created by li on 2016/10/17.
 */
public class SubscribeClient2 {
    String queueName;
    String exchangeName;
    String routingKey;
    String consumerTag= UUID.randomUUID().toString();
    Connection conn;
    Channel channel;
    boolean autoAck = true;

    public SubscribeClient2(String virtualHost, String userName, String password, String hostName, int portNumber,
                            String exchangeName, String routingKey, String queueName) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(userName);
        factory.setPassword(password);
        factory.setVirtualHost(virtualHost);
        factory.setHost(hostName);
        factory.setPort(portNumber);
        conn = factory.newConnection();
        channel = conn.createChannel();
        channel.queueDeclare(queueName, false, false, false, null);
        this.queueName = queueName;
        final String queueNameUse = queueName;
        //channel.exchangeDeclare(exchangeName, exchangeType, true);
        channel.queueDeclare(queueName, false, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);
        channel.basicConsume(queueName, true, consumerTag, new DefaultConsumer(channel) {
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body)
                    throws IOException {
                String routingKey = envelope.getRoutingKey();
                String contentType = properties.getContentType();
                long deliveryTag = envelope.getDeliveryTag();
                System.out.printf("客户端,收到消息，订阅队列[%s]，routingKey[%s],内容：%s\n", queueNameUse, routingKey, new String(body));
            }
        });
    }

    public void close() {
        try {
            channel.close();
        } catch (Exception e) {

        }
        try {
            conn.close();
        } catch (Exception e) {

        }
    }

}
